using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.WriteApi.Appcontext.Command;
using Yitter.IdGenerator;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	public class AssignPermissionsToRoleCommandHandler : IRequestHandler<AssignPermissionsToRoleCommand, bool>
	{
		private readonly IBaseRepository<RolePermission> _rpRepo;

		public AssignPermissionsToRoleCommandHandler(IBaseRepository<RolePermission> rpRepo)
		{
			_rpRepo = rpRepo;
		}

		public async Task<bool> Handle(AssignPermissionsToRoleCommand request, CancellationToken cancellationToken)
		{
			var olds = _rpRepo.GetAll().Where(x => ((RolePermission)x).RoleId == request.RoleId).Select(x => (RolePermission)x).ToList();
			if (olds.Count > 0) await _rpRepo.DeleteRangeAsync(olds);
			var news = request.PermissionIds.Distinct().Select(pid => new RolePermission { RolePermissionId = YitIdHelper.NextId(), RoleId = request.RoleId, PermissionId = pid }).ToList();
			if (news.Count > 0) await _rpRepo.AddRangeAsync(news);
			return true;
		}
	}
}
